import router from './router'
import store from './store'
import storage from 'store'
import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
import notification from 'ant-design-vue/es/notification'
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { i18nRender } from '@/locales'
import { getToken } from '@/utils/auth'
import { timeFix,clearBrowserCache } from '@/utils/util'
NProgress.configure({ showSpinner: false }) // NProgress Configuration
import Vue from 'vue'
const whiteList = ['login', 'register','bindMobile', 'forgotPasswd','registerResult','http://localhost:8080/swagger-ui.html',"socialLogin","socialLoginBinded"] // no redirect whitelist
const loginRoutePath = '/user/login'
const defaultRoutePath = '/dashboard/workplace'

router.beforeEach((to, from, next) => {
  // console.log("进入前" ,to.path,to.params)
  NProgress.start() // start progress bar
  to.meta && (typeof to.meta.title !== 'undefined' && setDocumentTitle(`${i18nRender(to.meta.title)} - ${domTitle}`))
  /* has token */
  // console.log(storage.get(ACCESS_TOKEN))
  if (getToken()) {
    //用户判断显不显示“登录状态失效”提示，第一次访问平台不显示
    sessionStorage.setItem("normalLogoutBool",false)

    if (to.path === loginRoutePath) {
      next({ path: defaultRoutePath })
      NProgress.done()
    } else {
      // check login user.roles is null
      // console.log(store)
      // console.log(store.getters)
      if (store.getters.roles.length === 0) {
        // request login userInfo
        store
          .dispatch('GetInfo')
          .then(res => {
            // const roles = res.result && res.result.role
            const roles = res.roles
            // generate dynamic router
            // console.log('================roles=====================')
            // console.log(roles)
            store.dispatch('GenerateRoutes', { roles }).then(() => {
              // 根据roles权限生成可访问的路由表
              // 动态添加可访问路由表
              router.addRoutes(store.getters.addRouters)
              if('login' == from.name){
                setTimeout(() => {
                  notification.success({
                    message: '欢迎',
                    description: `${timeFix()}，欢迎回来`
                  })
                }, 1000)
              }
              // 请求带有 redirect 重定向时，登录自动重定向到该地址
              const redirect = decodeURIComponent(from.query.redirect || to.path)
              if (to.path === redirect) {
                // set the replace: true so the navigation will not leave a history record
                next({ ...to, replace: true })
              } else {
                // 跳转到目的路由
                next({ path: redirect })
              }
            })
          })
          .catch(() => {
              
          })
      } else {
        if(decodeURIComponent(from.query.redirect || to.path) === '/' && from.name == 'login'){next({ path: '/dashboard/workplace' })}
        else{
          next()
       }
      }
    }
  } else {
    if (whiteList.includes(to.name)) {
      // 在免登录白名单，直接进入
      next()
    } else {

      //正常退出不提示登录状态失效
      if(sessionStorage.getItem("normalLogoutBool") === 'false'
      && sessionStorage.getItem("normalLogoutBool") != null){
        notification.error({
          message: '错误',
          description: '登录状态失效，请重新登录！'
        })
      }
      //退出就删除
      sessionStorage.removeItem("normalLogoutBool")
      //退出就清除浏览器缓存
      clearBrowserCache()

      // next({ path: loginRoutePath, query: { redirect: to.fullPath && to.fullPath != '/' ? to.fullPath : '' } })
      next({ path: loginRoutePath, query: { redirect: '' } })
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

router.afterEach((route ) => {
  NProgress.done() // finish progress bar
  console.log("进入后" ,route.path,route.params)
  window.current_component_globle_level_params_route = route.path
  // console.log(window.vm_tgz_reload())
  //特殊处理存入
  if("/sys/SysdictType/SysdictData" == route.path
    || "/product/SAAS/ProList/ProDeTail" == route.path
    || "/user/UserIndex/UserDeTail" == route.path){
     if(route.params && JSON.stringify(route.params) !="{}"){
        window.localStorage.setItem(route.path + "_keep_alive_logic_", JSON.stringify(route.params));
     }
  }
})
